var performancingEditor = {
    supportsSlugs : false,
    
	stateFilename : "performancing-editor-state.xml",
	stateArchiveFile : "performancing-editor-state-old.xml",
	
	restoreStateIndex : 0,
	autoSaveTimer : null,
	
	load : function () {
		if (gPerformancingUtil.prefs.getBoolPref("display.autosave")) {
			this.startAutoSave();
		}
	},
	
	startAutoSave : function () {
		this.autoSaveTimer = setInterval(function () { performancingEditor.autoSave(); }, 1000 * 30);
	},
	
	stopAutoSave : function () {
		clearTimeout(this.autoSaveTimer);
	},
	
	updateDateCreated : function () {
		document.getElementById("pff-edit-timestamp").checked = true;
	},
	
	autoSave : function () {
		if ((this.getEntryType() == 'note' || !this.getEntryType()) && (this.getTitle() || this.getContent().replace(/<br\s*\/?>/g, ""))) {
			if (!this.getEntryId()) {
				SCRIBEFIRE_NOTES.doSave(true);
			}
			else {
				SCRIBEFIRE_NOTES.reSaveNote();
			}
		}
		
		performancingEditor.saveState();
	},
	
	saveState : function () {
		var db = SCRIBEFIRE_DB.getDB();
		
		db.executeSimpleSQL("DELETE FROM "+SCRIBEFIRE_DB.stateTable);

		if (gPerformancingUtil.prefs.getBoolPref("settings.saveonexit")){
			var panels = document.getElementById("editor-tabbox").getElementsByTagName("iframe");
			
			for (var i = 0; i < panels.length; i++) {
				var panel = panels[i];
				
				try {
					var theType = this.getEntryType(panel);
					var entryId = this.getEntryId(panel);
					if (!entryId) entryId = '';
					
					var originalDateCreated = performancingEditor.getWindowForPanel(panel).pffEditorUI.originalDateCreated;
					
					var content = this.getContent(panel);
					var title = this.getTitle(panel);
					var tags = this.getTags(panel);
					var categories = this.getCategories(panel).join(",");
					var isDraft = (this.getEntryIsDraft(panel)) ? 1 : 0;
				
					var insert = db.createStatement("INSERT INTO "+SCRIBEFIRE_DB.stateTable+" (type, entryId, originalDateCreated, content, title, tags, categories, isDraft) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)");
					insert.bindStringParameter(0, theType);
					insert.bindStringParameter(1, entryId);
					insert.bindStringParameter(2, originalDateCreated);
					insert.bindUTF8StringParameter(3, content);
					insert.bindUTF8StringParameter(4, title);
					insert.bindUTF8StringParameter(5, tags);
					insert.bindUTF8StringParameter(6, categories);
					insert.bindInt32Parameter(7, isDraft);
					insert.execute();
				} catch (e) {
				}
			}
		}
		
		SCRIBEFIRE_DB.closeDB(db);
	},
	
	restoreState : function () {
		var file = gPerformancingUtil.getFilePath(performancingEditor.stateFilename);
		var theXMLString = PerFormancingFileIO.read(file, "UTF-8");
		
		if (theXMLString) {
			var stateXML = new XML(theXMLString);
	
			var editors = stateXML..editor;
			
			// Delete the old file and filename.
			var oldFile = gPerformancingUtil.getFilePath(performancingEditor.stateFilename);
			PerFormancingFileIO.unlink(oldFile);
			
			if (editors.length() > 0) {
				performancingEditor.restoreStateIndex = 0;
				performancingEditor.newTab(true, performancingEditor.continueRestoreState, editors);
			}
			else {
				performancingEditor.newTab(true, performancingEditor.doBlogThis);
			}
		}
		else {
			var db = SCRIBEFIRE_DB.getDB();
			
			var editors = [];
			
			var select = db.createStatement("SELECT type,entryId,title,tags,categories,originalDateCreated,isDraft,content FROM " + SCRIBEFIRE_DB.stateTable);
			
			try {
				while (select.executeStep()) {
					var editor = {};
					editor.type = select.getString(0);
					editor.entryId = select.getString(1);
					editor.title = select.getUTF8String(2);
					editor.tags = select.getUTF8String(3);
					editor.categories = select.getUTF8String(4);
					editor.originalDateCreated = select.getString(5);
					editor.isDraft = (select.getInt32(6)) ? true : false;
					editor.content = select.getUTF8String(7);
					
					editors.push(editor);
				}
			} catch (e) {
			} finally {
				select.reset();
			}
			
			SCRIBEFIRE_DB.closeDB(db);
			
			if (editors.length > 0) {
				performancingEditor.restoreStateIndex = 0;
				performancingEditor.newTab(true, performancingEditor.continueRestoreState, editors);
			}
			else {
				performancingEditor.newTab(true, performancingEditor.doBlogThis);
			}
		}
		
		performancingEditor.setCustomTimestampBoxes();
	},
	
	continueRestoreState : function (editors) {
		var editorsLength = 0;
		
		try {
			editorsLength = editors.length();
		} catch (e) {
			editorsLength = editors.length;
		}
		
		var editor = editors[performancingEditor.restoreStateIndex];
		
		performancingEditor.setEntryType(editor.type.toString());
		performancingEditor.setEntryId(editor.entryId.toString());
		performancingEditor.setTitle(editor.title.toString());
		performancingEditor.setTags(editor.tags.toString());
		performancingEditor.setCategories(editor.categories.toString().split(","));
		performancingEditor.getCurrentEditorWindow().pffEditorUI.originalDateCreated = editor.originalDateCreated.toString();
		try { performancingEditor.setEntryIsDraft(editor.isDraft.toString() == "true"); } catch (e) { }
		performancingEditor.setContent(editor.content.toString());
		
		performancingEditor.tabChange(true);
		
		if (performancingEditor.restoreStateIndex != ( editorsLength - 1 )) {
			performancingEditor.restoreStateIndex++;
			performancingEditor.newTab(true, performancingEditor.continueRestoreState, editors);
		}
		else {
			var text = gPerformancingUtil.prefs.getComplexValue("blogThisText", Components.interfaces.nsISupportsString).data;
			
			if (text) {
				var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
				str.data = "";
				gPerformancingUtil.prefs.setComplexValue("blogThisText", Components.interfaces.nsISupportsString, str);
				performancingEditor.newTab(true, performancingEditor.blogThis, text);
			}
		}
	},
	
	doBlogThis : function () {
		var text = gPerformancingUtil.prefs.getComplexValue("blogThisText", Components.interfaces.nsISupportsString).data;
		
		if (text) {
			var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
			str.data = "";
			gPerformancingUtil.prefs.setComplexValue("blogThisText", Components.interfaces.nsISupportsString, str);
			performancingEditor.blogThis(text);
		}
	},
	
	blogThis : function (text) {
		var theTab = performancingEditor.insertText(text);
		
		performancingEditor.getCurrentEditorWindow().performancingMidas.syncNormalTab();
	},
	
	getTitle : function (panel) {
		panel = performancingEditor.getEditorDocument(panel);
		
		return panel.getElementById("performancing-editor-subject").value.replace(/^\s+|\s+$/g, "");
	},
	
	setTitle : function (theTitle) {
		performancingEditor.getCurrentEditorDocument().getElementById("performancing-editor-subject").value = theTitle;
		performancingEditor.getCurrentEditorWindow().pffEditorUI.setTabTitle(theTitle);
	},
	
	prepContent : function (callback) {
		// Sync the Rich Text Tab
		
		var theDocument = performancingEditor.getCurrentEditorDocument();
		var tabbox = theDocument.getElementById("performancing-editor-tabbox");
		
		if (tabbox.selectedIndex == 1) {
			performancingEditor.getCurrentEditorWindow().performancingMidas.syncNormalTab(continue_prep);
		}
		else {
			continue_prep();
		}
		
		function continue_prep() {
			// Upload any images that are referenced via file:// URIs.
			var panel = performancingEditor.getCurrentEditorDocument();
			
			var midas = panel.getElementById("performancing-message");
			var doc = midas.contentDocument;
			
			if ("prepContent" in SCRIBEFIRE_BLOG.serviceObject) {
				doc = SCRIBEFIRE_BLOG.serviceObject.prepContent(doc);
			}
			
			var images = doc.getElementsByTagName("img");
			
			var shownAlert = false;
			
			for (var i = 0; i < images.length; i++) {
				if (images[i].getAttribute("src").match(/^file:/)) {
					var src = images[i].getAttribute("src");
				
					/*
					if (src.match(/^file:\/\/\/C:\//i)) {
						src = src.replace(/^file:\/\/\/C:\//i, "C:\\")
						src = src.replace(/\//g, "\\");
					}
					*/
				
					// Local image, need to upload.
					if (!shownAlert) {
						alert(performancingUI.getLocaleString("uploadLocalFiles"));
					}
				
					var uploadedURL = performancingUI.openImageUpload(src, shownAlert);
					
					if (uploadedURL) {
						images[i].setAttribute("src", uploadedURL);
					}
					else {
					    performancingUI.onProgressOff();
                    
						return false;
					}
				
					shownAlert = true;
				}
			}
			
			performancingEditor.getCurrentEditorWindow().performancingMidas.syncSourceTab();
			
			performancingEditor.getCurrentEditorWindow().SF_ZEMANTA.addUniversalTracker(callback);
		}
		
		return true;
	},
	
	getContent : function (panel) {
		panel = performancingEditor.getEditorDocument(panel);
		
		// Return the HTML for the currently selected editor
		var theDocument = panel;
		var editorDeck = theDocument.getElementById("performancing-editor-tabbox");
		
		var theContent = null;
		
		if (editorDeck.selectedIndex == 1) {
			theContent = theDocument.getElementById("performancing-message-source").value;
		}
		else {
			theContent = performancingEditor.getEditorDocument(theDocument.getElementById("performancing-message")).body.innerHTML;
			
			if (theContent.match(/<pre[^>]*>/i)) {
				try {
					var toReplace = theContent.match(/<pre[^>]*>([\s\S]+?)<\/pre>/im)[1];
					
					var replaced = toReplace.replace(/<br\s*\/?>/g,"\n");
					replaced = replaced.replace(/&lt;/g, "<");
					replaced = replaced.replace(/&gt;/g, ">");
					
        			// $ is a special backreference char.
        			replaced = replaced.replace(/\$/g, "$$$$");

					theContent = theContent.replace(toReplace, replaced);
				} catch (e) {
				}
			}
		}
		
		theContent = theContent.replace(/^\s+|\s+$/g, "");
		
		return theContent;
    },

	setContent : function (theContent) {
		var theDocument = performancingEditor.getCurrentEditorDocument();
		var editorDeck = theDocument.getElementById("performancing-editor-tabbox");
		
		// Open up the last edit mode that the user was using.
		try {
			var lastOpenedEditTab = gPerformancingUtil.prefs.getCharPref('display.state.lastviewopened');
		} catch(e) {
			var lastOpenedEditTab = "tab-normal-edit";
		}

		if (lastOpenedEditTab == 'tab-source-edit'){
			performancingEditor.getCurrentEditorWindow().performancingMidas.viewTab(theDocument.getElementById("tab-source-edit"));
			theDocument.getElementById("performancing-message-source").value = theContent;
		} 
		else {
			theDocument.getElementById("performancing-message-source").value = theContent;
			
			function callback() {
			    performancingEditor.getCurrentEditorWindow().performancingMidas.viewTab(theDocument.getElementById("tab-normal-edit"));
		    }
			
			performancingEditor.getCurrentEditorWindow().performancingMidas.syncNormalTab(callback);
		}
	},

	setEntryType : function (type) {
		performancingEditor.getCurrentEditorWindow().pffEditorUI.type = type;
		var theDocument = performancingEditor.getCurrentEditorDocument();
		
		switch (type) {
			case 'page':
				theDocument.getElementById("note-save-deck").selectedIndex = 0;
			break;
			case 'post':
				theDocument.getElementById("note-save-deck").selectedIndex = 0;
			break;
			case 'note':
			default:
				if (performancingEditor.getEntryId()) {
					theDocument.getElementById("note-save-deck").selectedIndex = 1;
				}
				else {
					theDocument.getElementById("note-save-deck").selectedIndex = 0;
				}
			break;
		}
	},
	
	getEntryType : function (panel) {
		if (!panel) panel = performancingEditor.getCurrentEditorWindow();
		else panel = performancingEditor.getWindowForPanel(panel);
		
		return panel.pffEditorUI.type;
	},
	
	getEntryId : function (panel) {
		if (!panel) panel = performancingEditor.getCurrentEditorWindow();
		else panel = performancingEditor.getWindowForPanel(panel);
		
		return panel.pffEditorUI.entryId;
	},
	
	setEntryId : function (id) {
		try {
			performancingEditor.getCurrentEditorWindow().pffEditorUI.entryId = id;
		
			var theDocument = performancingEditor.getCurrentEditorDocument();
		
			if (id && (performancingEditor.getEntryType() == 'page' || performancingEditor.getEntryType() == "post")) {
				theDocument.getElementById("note-save-deck").selectedIndex = 0;
			}
			else if (id) {
				theDocument.getElementById("note-save-deck").selectedIndex = 1;
			}
		} catch (e) { 
			alert("Error setting entryId: " + e);
		} 
	},
	
	setEntryIsDraft : function (isDraft) {
		performancingEditor.getCurrentEditorWindow().pffEditorUI.isDraft = isDraft;
	},
	
	getEntryIsDraft : function (panel) {
		if (!panel) panel = performancingEditor.getCurrentEditorWindow();
		else panel = performancingEditor.getWindowForPanel(panel);
		
		return panel.pffEditorUI.isDraft;
	},

	getTags : function (panel) {
		if (!panel) panel = performancingEditor.getCurrentEditorWindow();
		else panel = performancingEditor.getWindowForPanel(panel);

		return panel.pffEditorUI.tags;
	},

	setTags : function (tags) {
		performancingEditor.getCurrentEditorWindow().pffEditorUI.tags = tags;
	},
	
	setCategories : function (categories) {
		performancingEditor.getCurrentEditorWindow().pffEditorUI.categories = categories;
	},
	
	getCategories : function (panel) {
		if (!panel) panel = performancingEditor.getCurrentEditorWindow();
		else panel = performancingEditor.getWindowForPanel(panel);
		
		var categories = panel.pffEditorUI.categories;
		
		if (categories) return categories;
		return [];
	},
	
	updateCategories : function () {
		var catArray = [];
		
		var cbs = document.getElementById("blog-sidebar-listing-categories").getElementsByTagName("checkbox");
		
		for (var i = 0; i < cbs.length; i++) {
			if (cbs[i].checked) catArray.push(cbs[i].getAttribute("label"));
		}
		
		performancingEditor.setCategories(catArray);
	},
	
	setSlug : function (slug) {
	    performancingEditor.getCurrentEditorWindow().pffEditorUI.slug = slug;
    },

	setCustomFields : function (custom_fields) {
		var real_custom_fields = [];
		
		for (var i = 0; i < custom_fields.length; i++) {
			if (custom_fields[i].key[0] != "_") {
				real_custom_fields.push(custom_fields[i]);
			}
		}
		
		performancingEditor.getCurrentEditorWindow().pffEditorUI.custom_fields = real_custom_fields;
	},
	
	setOriginalDateCreated : function (dateCreated) {
		if (typeof dateCreated == "string") {
			dateCreated = new Date(dateCreated);
		}
		
		performancingEditor.getCurrentEditorWindow().pffEditorUI.originalDateCreated = dateCreated;
	},
	
	addMedia : function (path) {
		performancingEditor.getCurrentEditorWindow().pffEditorUI.media.unshift(path);
	},
	
	getMedia : function () {
		return performancingEditor.getCurrentEditorWindow().pffEditorUI.media;
	},
	
	getDateCreatedForNewPost : function (panel) {
		if (!panel) panel = performancingEditor.getCurrentEditorWindow();
		else panel = performancingEditor.getWindowForPanel(panel);
		
		if (document.getElementById("pff-edit-timestamp").checked) {
			return performancingEditor.getCustomDateCreated();
		}
		else {
			return new Date();
		}
	},
	
	getDateCreatedForRepublish : function (panel) {
		if (!panel) panel = performancingEditor.getCurrentEditorWindow();
		else panel = performancingEditor.getWindowForPanel(panel);
		
		if (document.getElementById("pff-edit-timestamp").checked) {
			return performancingEditor.getCustomDateCreated();
		}
		else {
			return panel.pffEditorUI.originalDateCreated;
		}
	},
	
	getCustomDateCreated : function () {
		function pad(n) {
			if (n < 10) { return "0" + (n/1); }
			return n;
		}
		
		var timestamp = document.getElementById("pff-post-time-year").value + "/"
			+ pad(document.getElementById("pff-post-time-month").value) + "/"
			+ pad(document.getElementById("pff-post-time-day").value) + " "
			+ pad(document.getElementById("pff-post-time-hour").value) + ":"
			+ pad(document.getElementById("pff-post-time-minute").value) + ":00";
		
		var date = new Date(timestamp);
		return date;
	},

	getCurrentEditorDocument : function () {
		var tabbox = document.getElementById("editor-tabbox");
		var theTab = tabbox.selectedIndex;
		var thePanel = tabbox.getElementsByTagName("iframe")[theTab];
		
		if (thePanel.contentDocument.wrappedJSObject) {
			return thePanel.contentDocument.wrappedJSObject;
		}
		else {
			return thePanel.contentDocument;
		}
	},
	
	getEditorDocument : function (panel) {
		if (!panel) return performancingEditor.getCurrentEditorDocument();
		
		if (panel.contentDocument.wrappedJSObject) {
			return panel.contentDocument.wrappedJSObject;
		}
		
		return panel.contentDocument;
	},
	
	getCurrentEditorWindow : function () {
		var tabbox = document.getElementById("editor-tabbox");
		var theTab = tabbox.selectedIndex;
		var thePanel = tabbox.getElementsByTagName("iframe")[theTab];
		
		return performancingEditor.getWindowForPanel(thePanel);
	},
	
	getWindowForPanel : function (panel) {
		if (panel.contentWindow.wrappedJSObject) {
			return panel.contentWindow.wrappedJSObject;
		}
		
		return panel.contentWindow;
	},
	
	selectTabForEntry : function (type, entryId) {
		var panels = document.getElementById("editor-tabbox").getElementsByTagName("iframe");
		
		var tabbox = document.getElementById("editor-tabbox");
		var theTab = tabbox.selectedIndex;
		
		try {
			for (var i = 0; i < panels.length; i++) {
				if (performancingEditor.getWindowForPanel(panels[i]).pffEditorUI.type == type) {
					if (performancingEditor.getWindowForPanel(panels[i]).pffEditorUI.entryId == entryId) {
						// Select this panel.
						var tabbox = document.getElementById("editor-tabbox");
						tabbox.selectedIndex = i;
						return true;
					}
				}
			}
		} catch (probablyDoesntMatter) {
		}
		
		return false;
	},
	
	lastZemantaImage : null,
	
	insertZemantaImage : function (image) {
		var code = '<div class="zemanta-image" style="float: right;"><a href="' + image.reference.source_url + '" title="'+image.reference.license+'"><img src="';
		
		if (image.reference.url_l_w > 300) {
			code += image.reference.url_m;
		}
		else {
			code += image.reference.url_l;
		}
		
		code += '" /></a>';
		
		if (image.reference.attribution) {
			code += '<br /><small>' + image.reference.attribution;
		}
		
		code += '</small></div>';
		
		var theDocument = performancingEditor.getCurrentEditorDocument();
		var tabbox = theDocument.getElementById("performancing-editor-tabbox");
		
		if (tabbox.selectedIndex != 1) {
			performancingEditor.getCurrentEditorWindow().performancingMidas.syncSourceTab();
		}

		var postText = theDocument.getElementById("performancing-message-source").value;
		
		if (code == this.lastZemantaImage) {
    		var newText = postText.replace(/<div class="zemanta-image"[\s\S]+?<\/div>/im, "");

    		theDocument.getElementById("performancing-message-source").value = newText;
    		
    		this.removeZemantaSignature();
    		
		    this.lastZemantaImage = null;
	    }
	    else {
    		var newText = postText.replace(/<div class="zemanta-image"[\s\S]+?<\/div>/im, code);
    		
    		if (newText == postText) newText = code + postText;

    		theDocument.getElementById("performancing-message-source").value = newText;

		    this.insertZemantaSignature();

    		this.lastZemantaImage = code;
        }
		
		if (tabbox.selectedIndex != 1) {
			performancingEditor.getCurrentEditorWindow().performancingMidas.syncNormalTab();
		}
	},
	
	insertZemantaArticles : function () {
		var articles = document.getElementById("zemanta-articles-container").childNodes;
		
		var codePrefix = '<div class="zemanta-articles">Related articles by Zemanta:<ul class="zemanta-articles">';
		var code = '';
		
		for (var i = 0; i < articles.length; i++) {
			if (articles[i].getAttribute("active") == "true") {
				code += '<li><a href="'+articles[i].reference.url+'">'+articles[i].reference.title+'</a></li>';
			}
		}
		
		codePostfix = '</ul></div>';
		
		if (code != '') {
			code = codePrefix + code + codePostfix;
		}
		else {
			code = '';
		}
		
		var theDocument = performancingEditor.getCurrentEditorDocument();
		var tabbox = theDocument.getElementById("performancing-editor-tabbox");
		
		if (tabbox.selectedIndex != 1) {
			performancingEditor.getCurrentEditorWindow().performancingMidas.syncSourceTab();
		}

		var postText = theDocument.getElementById("performancing-message-source").value;
		
		var newText = postText.replace(/(\n\n)?(<br \/><br \/>)?<div class="zemanta-articles">[\s\S]+?<\/ul><\/div>/gi, "");
		newText += '<br /><br />' + code;
	
		theDocument.getElementById("performancing-message-source").value = newText;
		
		this.insertZemantaSignature();
		
		if (tabbox.selectedIndex != 1) {
			performancingEditor.getCurrentEditorWindow().performancingMidas.syncNormalTab();
		}
	},
	
	removeZemantaSignature : function () {
		var theDocument = performancingEditor.getCurrentEditorDocument();
		var tabbox = theDocument.getElementById("performancing-editor-tabbox");
		var postText = theDocument.getElementById("performancing-message-source").value;
		
		var newText = postText.replace(/(\n\n)?(<br( \/)?><br( \/)?>)?<div class="zemanta-pixie">[\s\S]+<\/div>/gi, "");
		theDocument.getElementById("performancing-message-source").value = newText;
		
		performancingEditor.getCurrentEditorWindow().SF_ZEMANTA.signatureInserted = false;
    },
    
	insertZemantaSignature : function (callback) {
	    if (callback) {
	        var theDocument = performancingEditor.getCurrentEditorDocument();
		    var tabbox = theDocument.getElementById("performancing-editor-tabbox");
		
		    if (tabbox.selectedIndex != 1) {
			    performancingEditor.getCurrentEditorWindow().performancingMidas.syncSourceTab();
		    }
        }
        
		var theDocument = performancingEditor.getCurrentEditorDocument();
		var tabbox = theDocument.getElementById("performancing-editor-tabbox");
		var postText = theDocument.getElementById("performancing-message-source").value;
		
		var newText = postText.replace(/(\n\n)?(<br( \/)?><br( \/)?>)?<div class="zemanta-pixie">[\s\S]+?<\/div>/gi, "");
		theDocument.getElementById("performancing-message-source").value = newText + "<br /><br />" + performancingEditor.getCurrentEditorWindow().SF_ZEMANTA.signature;
		performancingEditor.getCurrentEditorWindow().SF_ZEMANTA.signatureInserted = true;
		
		if (callback) {
    		if (tabbox.selectedIndex != 1) {
    			performancingEditor.getCurrentEditorWindow().performancingMidas.syncNormalTab(callback);
    		}
			else {
				callback();
			}
	    }
	},
	
	insertText : function (text, isPlainText) {
		// Appends some text to the current editor's content
		var theDocument = performancingEditor.getCurrentEditorDocument();
		
	    var tabbox = theDocument.getElementById("performancing-editor-tabbox");
		
		if (isPlainText && tabbox.selectedIndex != 1) {
			performancingEditor.getCurrentEditorWindow().performancingTextEdit.insertAtCursor(text);
		}
		else {
			if (tabbox.selectedIndex != 1) {
				performancingEditor.getCurrentEditorWindow().performancingMidas.syncSourceTab();
				theDocument.getElementById("performancing-message-source").setSelectionRange(theDocument.getElementById("performancing-message-source").value.length, theDocument.getElementById("performancing-message-source").value.length);
			}

			var preText = theDocument.getElementById("performancing-message-source").value.substring(0, theDocument.getElementById("performancing-message-source").selectionStart);
			var postText = theDocument.getElementById("performancing-message-source").value.substring(theDocument.getElementById("performancing-message-source").selectionEnd);
		
			var newText = preText + text + postText;
		
			theDocument.getElementById("performancing-message-source").value = newText;
		
			theDocument.getElementById("performancing-message-source").setSelectionRange(preText.length + text.length, preText.length + text.length);
		
			if (!isPlainText && tabbox.selectedIndex != 1) {
				performancingEditor.getCurrentEditorWindow().performancingMidas.syncNormalTab();
			}
		}
	},
	
	setUseCSS : function (flag) {
		var panels = document.getElementById("editor-tabbox").getElementsByTagName("iframe");
		
		for (var i = 0; i < panels.length; i++) {
			var midas = performancingEditor.getEditorDocument(panels[i]).getElementById("performancing-message");
			performancingEditor.getEditorDocument(midas).execCommand("styleWithCSS", false, flag);
		}
	},
	
	setEditorStyle : function (theStyle) {
		var panels = document.getElementById("editor-tabbox").getElementsByTagName("iframe");
		
		for (var i = 0; i < panels.length; i++) {
			try {
				performancingEditor.getEditorDocument(performancingEditor.getEditorDocument(panels[i]).getElementById("performancing-preview-display")).contentDocument.getElementsByTagName("body")[0].setAttribute('style', theStyle);
			} catch(e) { }

			try {
				performancingEditor.getEditorDocument(performancingEditor.getEditorDocument(panels[i]).getElementById("performancing-message")).getElementById("performancing-richtext").setAttribute('style', theStyle);
			} catch(e) { }

			try {
				performancingEditor.getEditorDocument(panels[i]).getElementById("performancing-editor-subject").setAttribute('style', theStyle);
			} catch(e) { }

			try {
				performancingEditor.getEditorDocument(panels[i]).getElementById("performancing-message-source").setAttribute('style', theStyle);
			} catch(e) { }
		}
	},
	
	postSuccessful : function () {
		var theDocument = performancingEditor.getCurrentEditorDocument();
		var thePublishDeck = theDocument.getElementById('performancing-feedback-deck');
		thePublishDeck.setAttribute('selectedIndex','0');
		theDocument.getElementById("editor-buttons-bottom").setAttribute("collapsed","true");
		
		window.clearTimeout(gPffOnPublishTimeOut);
	},
	
	setSplitterButton : function (disabled) {
		var panels = document.getElementById("editor-tabbox").getElementsByTagName("iframe");
		
		for (var i = 0; i < panels.length; i++) {
			try {
				performancingEditor.getEditorDocument(panels[i]).getElementById("cmd_splitter").setAttribute("disabled", disabled.toString());
			} catch (e) {
			}
		}
	},
	
	tabClick : function (event) {
		if (event.which == 2 || (event.which == 1 && event.metaKey)) {
			performancingEditor.closeTab();
		}
	},
	
	tabIsBlank : function (panel) {
		if (!this.getEntryId(panel)) {
			if (!this.getTitle(panel)) {
				var tabContent = this.getContent(panel).replace(/<br\s*\/?>/g, " ").replace(/\s/g, "");
				
				if (!tabContent) {
					return true;
				}
			}
		}
		
		return false;
	},
	
	newTab : function (selectIt, callback, args) {
		var tabs = document.getElementById("tabs-parent");
		var panels = document.getElementById("panels-parent");
		
		// Check for a blank tab at the end.
		
		if (panels.childNodes.length > 0) {
			var lastPanel = panels.childNodes[panels.childNodes.length - 1];
		}
		
		if (lastPanel && callback && performancingEditor.tabIsBlank(lastPanel)) {
			document.getElementById("editor-tabbox").selectedIndex = panels.childNodes.length - 1;
			performancingEditor.getCurrentEditorWindow().pffEditorUI.clearAll();
			callback(args);
			return;
		}
		else {
			var newTab = document.createElement("tab");
			newTab.setAttribute("label", performancingUI.getLocaleString("blankTabLabel"));
			newTab.setAttribute("onclick", "performancingEditor.tabClick(event);");
			newTab.setAttribute("class","tabbrowser-tab");

			tabs.appendChild(newTab);
		
			var lastPanel = document.createElement("iframe");
			lastPanel.setAttribute("src", "chrome://scribefire/content/editor/editor.xul");
			lastPanel.setAttribute("flex", "1");
		
			panels.appendChild(lastPanel);
		
			if (selectIt) {
				document.getElementById("editor-tabbox").selectedIndex = panels.childNodes.length - 1;
			}
		}
		
		if (callback) {
			try {
				var x = performancingEditor.getWindowForPanel(lastPanel).pffEditorUI.type;
			} catch (e) {
				performancingEditor.getWindowForPanel(lastPanel).addEventListener("load", function (event) { callback(args); }, false);
				return;
			}
			
			callback(args);
		}
		else {
			performancingEditor.getWindowForPanel(lastPanel).addEventListener("load", function (event) { performancingEditor.blankEntry(); }, false);
		}
	},
	
	setCustomTimestampBoxes : function () {
		if (!document.getElementById("pff-post-time-year").value || !document.getElementById("pff-edit-timestamp").checked) {
			function pad(n) {
				if (n < 10) { return "0" + (n/1); }
				return n;			
			}
	
			var dateCreated = new Date();
	
			document.getElementById("pff-post-time-year").value = dateCreated.getFullYear();
			document.getElementById("pff-post-time-month").value = pad(dateCreated.getMonth() + 1);
			document.getElementById("pff-post-time-day").value = pad(dateCreated.getDate());
	
			document.getElementById("pff-post-time-hour").value = pad(dateCreated.getHours());
			document.getElementById("pff-post-time-minute").value = pad(dateCreated.getMinutes());
		}
	},
	
	blankEntry : function () {
		performancingEditor.setEntryId();
		performancingEditor.setEntryType("note");
		performancingEditor.setEntryIsDraft(gPerformancingUtil.prefs.getBoolPref("publish.checkdraft"));
		
		var theDocument = performancingEditor.getCurrentEditorDocument();
		var editorDeck = theDocument.getElementById("performancing-editor-tabbox");
		
		// Open up the last edit mode that the user was using.
		try {
			var lastOpenedEditTab = gPerformancingUtil.prefs.getCharPref('display.state.lastviewopened');
		} catch(e) {
			var lastOpenedEditTab = "tab-normal-edit";
		}

		if (lastOpenedEditTab == 'tab-source-edit'){
			performancingEditor.getCurrentEditorWindow().performancingMidas.viewTab(theDocument.getElementById("tab-source-edit"));
		} 
		else {
			performancingEditor.getCurrentEditorWindow().performancingMidas.viewTab(theDocument.getElementById("tab-normal-edit"));
		}
	},
	
	closeTab : function (force, newtabCallback, args) {
		if (!force) force = !gPerformancingUtil.prefs.getBoolPref("confirmTabClose");
		var rv = false;
		var tempstring = performancingUI.getLocaleString('confirmtabdelete');
		
		if (force || confirm(tempstring)) {
			var tabbox = document.getElementById("editor-tabbox");
		
			var idx = tabbox.selectedIndex;
			var panels = tabbox.getElementsByTagName("iframe");
			var tabs = tabbox.getElementsByTagName("tab");
			var panel = panels[idx];
			var tab = tabs[idx];
		
			if (tabs.length == 1){
				rv = true;
				performancingEditor.newTab(true, newtabCallback, args);
			}
		
			panel.parentNode.removeChild(panel);
			tab.parentNode.removeChild(tab);
		
			var panels = tabbox.getElementsByTagName("iframe");
			var tabs = tabbox.getElementsByTagName("tab");
		
			tabbox.selectedPanel = panels[Math.min(idx, panels.length - 1)];
			tabbox.selectedTab = tabs[Math.min(idx, tabs.length - 1)];
		}
		
		return rv;
	},
	
	keepContent : function () {
		var title = this.getTitle();
		var content = this.getContent();
		
		var openedNewTab = this.closeTab(true, performancingEditor.continueKeepContent, [ title, content ]);
		
		if (!openedNewTab) {
			this.newTab(true, performancingEditor.continueKeepContent, [ title, content ]);
		}
	},
	
	continueKeepContent : function (argArray) {
		performancingEditor.setTitle(argArray[0]);
		performancingEditor.setContent(argArray[1]);
		performancingEditor.setEntryType("note");
		performancingEditor.setEntryId();
	},
	
	tabChange : function () {
		try {
			var ob = performancingEditor.getCurrentEditorWindow().pffEditorUI;
		
			// What needs to happen here:
			// Select the item from this history / note / page list.
			// Show the history / note / page list.
			switch (ob.type) {
				case 'note':
					if (ob.entryId) {
						document.getElementById("entries-tabs").selectedIndex = 1;
						document.getElementById("entries-deck").selectedIndex = 1;
						
						var list = document.getElementById("performancing-notes-list");
					}
				break;
				case 'page':
					document.getElementById("entries-tabs").selectedIndex = 2;
					document.getElementById("entries-deck").selectedIndex = 2;

					var list = document.getElementById("performancing-pages-list");
				break;
				case 'post':
					document.getElementById("entries-tabs").selectedIndex = 0;
					document.getElementById("entries-deck").selectedIndex = 0;
					
					var list = document.getElementById("performancing-history-list");
				break;
			}
		
			if (list) {
				var items = list.getElementsByTagName("listitem");
			
				list.selectedIndex = -1;
			
				for (var i = 0; i < items.length; i++) {
					if (items[i].getAttribute("postid") == ob.entryId) {
						list.selectedIndex = i;
					}
				}
			}
		
			var catCBs = document.getElementById("blog-sidebar-listing-categories").getElementsByTagName("checkbox");
			var categories = performancingEditor.getCategories()
		
			function in_array(a, v) {
				for (var i = 0; i < a.length; i++) {
					if (a[i] == v) {
						return true;
					}
				}
			
				return false;
			}
		
			for (var i = 0; i < catCBs.length; i++) {
				catCBs[i].checked = in_array(categories, catCBs[i].getAttribute("label"));
			}
		
			// Set the tags.
			document.getElementById("input-tags").value = ob.tags;
			
			document.getElementById("pff-edit-timestamp").checked = performancingEditor.getCurrentEditorWindow().pffEditorUI.timestampEdit;
			
			performancingUI.setBlogStatus();
		} catch (e) {
			performancingEditor.getCurrentEditorWindow().addEventListener("load", function (x) { performancingEditor.tabChange(true); }, false);
		}
	},
	
	setTimestampEdit : function (doEdit) {
		performancingEditor.getCurrentEditorWindow().pffEditorUI.timestampEdit = doEdit;
	},
	
	setPublishButtonLabel : function (label) {
		var panels = document.getElementById("editor-tabbox").getElementsByTagName("iframe");
	
		for (var i = 0; i < panels.length; i++) {
			try {
				performancingEditor.getEditorDocument(panels[i]).getElementById("performancing-publish-button").setAttribute("label", label);
			} catch (notLoadedYet) {
			}
		}
	}
};
